package cn.tedu.boot31.controller;

import cn.tedu.boot31.utils.DBUtils;
import cn.tedu.boot31.vo.Article;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@Controller
public class ArticleController {
    /*
    use empdb;
    create table article(id int primary key auto_increment,
    title varchar(20),author varchar(20),
    content varchar(50))charset=utf8;
    * */
    @RequestMapping("/createArticle")
    @ResponseBody
    public String createArticle(Article article){
        System.out.println("article="+article);
        //获取连接
        try (Connection conn = DBUtils.getConn()){
            String sql = "insert into article values(null,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,article.getTitle());
            ps.setString(2,article.getAuthor());
            ps.setString(3,article.getContent());
            ps.executeUpdate();//执行插入操作
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "添加完成!";
    }

    @RequestMapping("/showAllArticle")
    @ResponseBody
    public String showAllArticle(){
        ArrayList<Article> list = new ArrayList<>();
        //获取连接
        try (Connection conn = DBUtils.getConn()){
            String sql = "select * from article";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            //遍历结果集
            while(rs.next()){
                String title = rs.getString(2);
                String author = rs.getString(3);
                String content = rs.getString(4);
                list.add(new Article(title,author,content));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //把集合中的内容以字符串形式返回给客户端
        return list.toString();
//        //遍历集合把里面的数据装进一个html里面
//        String html = "<table border=1>";
//        html+="<caption>文章列表</caption>";
//        html+="<tr><th>文章标题</th><th>文章作者</th><th>文章内容</th></tr>";
//        for (Article article: list) {
//            html+="<tr>";
//            html+="<td>"+article.getTitle()+"</td>";
//            html+="<td>"+article.getAuthor()+"</td>";
//            html+="<td>"+article.getContent()+"</td>";
//            html+="</tr>";
//        }
//        html+="</table>";
//        return html;
    }
}
